﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using System.Drawing;

namespace System.Drawing.Imaging.Assist
{
    /// <summary>
    /// while and black bitmap process
    /// </summary>
    internal class BWProcess : ImageProcessBase
    {
        /// <summary>
        /// init function
        /// </summary>
        /// <param name="image"></param>
        public BWProcess(Bitmap image) : base(image) { }

        /// <summary>
        /// Black and white processing algorithms
        /// </summary>
        /// <returns>Black and white images</returns>
        public override Bitmap ProcessImage()
        {
            BitmapData bitmapdata = Source.LockBits(new Rectangle(new Point(0, 0), Source.Size),
                    ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

            for (int i = 0; i < bitmapdata.Height * bitmapdata.Width; i++)
            {
                uint value = (uint)Marshal.ReadInt32(bitmapdata.Scan0, (i * 4));
                //tempvalue is the middle value,Black and white pixel RGB values are intermediate
                uint tempvalue = ((value >> 16 & 0xff) * 30 + (value >> 8 & 0xff) * 59 + (value & 0xff) * 11 + 50) / 100;
                //Rgb value set for the middle
                uint outvalue = (tempvalue) + (tempvalue << 8) + (tempvalue << 16) + (value & 0xff000000);

                Marshal.WriteInt32(bitmapdata.Scan0, (i * 4), (int)outvalue);
            }

            Source.UnlockBits(bitmapdata);

            return Source;
        }
    }
}
